package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dkm.orproject.dkmoa.domain.OaClient;
import com.dkm.orproject.dkmoa.domain.OaClientType;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.service.OaClientTypeService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.ThreeVo;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  @ClassName : OaClientTypeAction  //类名
 *  @Description : 客户类型控制层
 *  @Author : zmh //作者
 *  @Date: 2020-11-18 09:28  //时间
 */
@RestController
@RequestMapping("/OaClientTypeAction")
public class OaClientTypeAction {
    /**
     * 工具类
     */
    @Resource
    Tools tools;

    /**
     * 登陆人
     */
    OaPersonnel personnel;


    /**
     * 日志
     */
    OaLog log;

    /**
     * 客户类型service对象
     */
    @Resource
    OaClientTypeService oaClientTypeService;

    /**
     * 回调map
     */
    Map<String, Object> map;

    /**
     * 修改和增加客户类型的接口
     * @param oaClientType 客户类型模型对象
     * @param request 请求对象
     * @return 回调函数
     */
    @PostMapping("addOrUpdate")
    @UserLoginToken
    public Map<String,Object> addOrUpdate(OaClientType oaClientType, HttpServletRequest request){
        OaPersonnel oaPersonnel = (OaPersonnel) request.getSession().getAttribute("user");
        Map<String,Object> map = new HashMap<>();
        if(ObjectUtils.isEmpty(oaPersonnel)){
            tools.rowMap(map, 0, null);
        }try {
            int rows = 0;
            OaLog log = new OaLog();
            if(oaClientType.getPkClientTypeId()!=null && !"".equals(oaClientType.getPkClientTypeId())){
                oaClientType.setUpdatedBy(oaPersonnel.getPersonnelName());
                oaClientType.setUpdatedTime(new Date());
                log.setLogTitle("修改客户类型");
                rows = oaClientTypeService.updateByPrimaryKeySelective(oaClientType);
            }else {
                oaClientType.setCreatedBy(oaPersonnel.getPersonnelName());
                oaClientType.setIsRevision("1");
                if(oaClientType.getClientTypeSuperior()==null){
                    oaClientType.setClientTypeSuperior(0L);
                }
                log.setLogTitle("增加客户类型");
                rows = oaClientTypeService.insertSelective(oaClientType);
            }
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(oaPersonnel).toString());
            log.setLogType("1");
            tools.rowMap(map,rows,log);
            return map;
        }catch (Exception e){
            OaLog log = new OaLog();
            log.setLogBody(JSONObject.toJSON(e.getStackTrace()).toString());
            log.setLogTitle("客户类型增加或修改模块异常");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogType("0");
            log.setLogIp(request.getRemoteAddr());
            tools.errorMap(map, log);
            return map;
        }
    }

    /**
     *根据Id删除该条数据接口
     * @param pkClientTypeId
     * @param session 服务器会话
     * @param request 服务器请求
     * @return 回调函数
     */

    @DeleteMapping("deleteOaClientTypeById/{pkClientTypeId}")
    @UserLoginToken
    public Map<String, Object> deleteByPrimaryKey(@PathVariable("pkClientTypeId") Long pkClientTypeId, HttpSession session, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) session.getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        try {
            OaLog log = new OaLog();
            OaClientType oaClientType = new OaClientType();
            oaClientType.setPkClientTypeId(pkClientTypeId);
            oaClientType.setIsRevision("0");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogTitle("客户类型的删除模块");
            int rows = oaClientTypeService.deleteByPrimaryKey(pkClientTypeId);
            log.setLogIp(request.getRemoteAddr());
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(oaPersonnel).toString());
            tools.rowMap(map, rows, log);
            return map;
        } catch (Exception e) {
            OaLog log = new OaLog();
            log.setLogTitle("客户类型的删除模块异常");
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogType("0");
            tools.errorMap(map, log);
            return map;
        }

    }

    /**
     * 根据Id查询接口
     * @param pkClientTypeId 客户id值
     * @param request 请求对象
     * @return 客户类型模型
     */
    @GetMapping("findById/{pkClientTypeId}")
    @UserLoginToken
    public Map<String, Object> selectByPrimaryKey(@PathVariable("pkClientTypeId") Long pkClientTypeId, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) request.getSession().getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        try {
            OaClientType oaClientType = oaClientTypeService.selectByPrimaryKey(pkClientTypeId);
            OaLog log = new OaLog();
            log.setLogTitle("客户id查询模块查询成功");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogIp(request.getRemoteAddr());
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(oaPersonnel).toString());
            tools.rowMap(map, 1, null);
            map.put("data", oaClientType);
            return map;
        } catch (Exception e) {
            OaLog log = new OaLog();
            log.setLogTitle("客户类型根据id查询模块异常");
            log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogType("0");
            log.setLogIp(request.getRemoteAddr());
            tools.errorMap(map, log);
        }
        return map;
    }

    /**
     * 分页查询所有客户类型的接口
     * @param oaClientType
     * @param page 当前页数
     * @param limit 每页的行数
     * @param startTime 开始时间
     * @param endDate 结束时间
     * @param request 服务器请求对象
     * @return 所有客户类型的集合
     */

    @GetMapping("selectAll")
    @UserLoginToken
    public Map<String,Object> findAll(OaClientType oaClientType, Integer page, Integer limit, String startTime, String endDate, HttpServletRequest request){
        try {
            //查询总行数
            Long rowCount=oaClientTypeService.rowCount(oaClientType,startTime,endDate);
            //分页查询集合
            List<OaClientType> logs=oaClientTypeService.selectAll(oaClientType,startTime,endDate,page,limit);
            //返回集合
            return Tools.maps(logs,rowCount);
        } catch (Exception e) {
            OaPersonnel oaPersonnel= (OaPersonnel)request.getSession().getAttribute("user");
            Map<String,Object> map=new HashMap<>();
            OaLog log = new OaLog();
            log.setLogBody(JSONObject.toJSON(e.getStackTrace()).toString());
            log.setLogTitle("查询客户类型的所有方法");
            log.setLogType("0");
            log.setLogIp(request.getRemoteAddr());
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            tools.errorMap(map,log);
            return map;
        }
    }


    /**
     * 批量删除客户类型的接口
     * @param ids 要删除的客户类型id数组
     * @param session 服务器会话对象
     * @param request 服务器请求对象
     * @return 回调函数
     */
    @DeleteMapping("deleteAll")
    @UserLoginToken
    public Map<String, Object> deleteAll(@RequestParam(value = "ids[]", required = false) Long[] ids, HttpSession session, HttpServletRequest request) {
        OaPersonnel user = (OaPersonnel) session.getAttribute("user");
        List<Long> list;
        Map<String,Object> map=new HashMap<>();
        if (ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }else {
            //把数组转化为集合
            list = Arrays.asList(ids);
        }
        try {
            OaLog log = new OaLog();
            int deleteAll = oaClientTypeService.deleteAll(list);
            log.setLogType("1");
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(user).toString());
            log.setLogTitle("客户批量删除模块");
            log.setCreatedBy(user.getPersonnelName());
            tools.rowMap(map, deleteAll, log);
            map.put("data",deleteAll);
            return map;
        } catch (Exception e) {
            addErrorLog(request,"客户类型删除模块异常",e);
            return map;
        }
    }

    @UserLoginToken
    @GetMapping("loadOaClientType")
    public List<ThreeVo> loadClientType(Long id,String show,HttpServletRequest request){
       //获取当前人操作信息
        rowMap(request);
        //判断操作人是否存在
        if (ObjectUtils.isEmpty(personnel)){
            return null;
        }
        try {
            return oaClientTypeService.loadOaClientType(id,show);
        }catch (Exception e){
            addErrorLog(request,"客户类型查询所有",e);
        }
        return null;
    }

    /**
     * 收集报错日志
     *
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title   模块标题
     * @param e       异常参数
     */
    private void addErrorLog(HttpServletRequest request, String title, Exception e) {
        //后台打印报错信息
        e.printStackTrace();
        //获取当前操作人
        personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log = new OaLog();
        //日志类型
        log.setLogType("0");
        //日志内容
        log.setLogBody(e.getLocalizedMessage());
        //日志标题
        log.setLogTitle(title);
        //请求地址
        log.setLogIp(request.getRemoteAddr());
        //判断当前登陆人是否存在
        if (ObjectUtils.isEmpty(personnel)) {
            //当前操作人名称
            log.setCreatedBy(personnel.getPersonnelName());
        }
        //存入报错日志
        tools.errorMap(log);
    }


    /**
     * 优化代码 获取当前登陆人信息
     *
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request) {
        //新建返回Map模型
        map = new HashMap<>(16);
        //获取登陆人信息
        personnel = (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if (ObjectUtils.isEmpty(personnel)) {
            return;
        }
        //新建日志
        log = new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }


    /**
     * 日期格式化
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
